<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/2/20
 * Time: 16:46
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Member extends Base
{
    /**
     * 用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax()){
            $where['user_status'] = ['neq', 3];
//            $where['uson_status'] = ['neq', 3];
            $keyword = input('keyword');
            $start = input('start');
            $end = input('end');
            $user_status = input('user_status');
            $user_school = input('user_school');
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|uson_username|uson_idcard'] = ['like', '%' . $keyword . '%'];
            }
            
            if(isset($start) && $start != "" && isset($end) && $end == "")
            {
                $where['uson_year'] = ['>=',$start];
            }
            if(isset($end) && $end != "" && isset($start) && $start == "")
            {
                $where['uson_year'] = ['<=',$end];
            }
            if(isset($start) && $start != "" && isset($end) && $end != "")
            {
                $where['uson_year'] = ['between',[$start,$end]];
            }
            
            if(isset($user_school) && $user_school != "")
            {
                $where['uson_school'] = $user_school;
            }
            if(isset($user_status) && $user_status)
            {
                $where['user_status'] = $user_status;
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('u_user')
                ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
                ->join('up_school', 'school_id = uson_school', 'left')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('u_user')
                ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
                ->join('up_school', 'school_id = uson_school', 'left')
                ->where($where)
                ->field('user_id, user_dj_log, username, user_phone, user_username, school_name, user_time, 
                user_wx_token, user_status,uson_status,uson_id,uson_username,uson_idcard,user_gender,uson_year,uson_grade')
                ->page($NowPage,$limits)
                ->order('user_time desc')
                ->select();
            foreach ($lists as $key => $vo){
                if(!$vo['uson_status']) $lists[$key]['uson_status'] = '';
                if($vo['user_wx_token']){
                    $lists[$key]['wx'] = '是';
                }else{
                    $lists[$key]['wx'] = '否';
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->where('school_status', 1)
            ->order('school_time desc')
            ->select();
        $this->assign([
            'school' => $school,
        ]);
        return $this->fetch();
    }

    /**
     * 冻结
     * @return \think\response\Json
     */
    public function down(){
        $user_id = input('id');
        $logs = Db::table('up_u_user')->where('user_id', $user_id)->value('user_dj_log');
        if($logs){
            $logs .= '|' . session ('username') . '于' . date('Y-m-d H:i:s') . '冻结';
        }else{
            $logs = session ('username') . '于' . date('Y-m-d H:i:s') . '冻结';
        }
        $update = [
            'user_status' => 2,
            'user_dj_log' => $logs
        ];
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($update);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 启用
     * @return \think\response\Json
     */
    public function up(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 1);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 详情
     * @return mixed
     */
    public function memberDetail(){
        $user_id = input('user_id');
        $where = [
            'user_id' => $user_id
        ];
        $uson_id = trim(input('uson_id'),' ');
        if($uson_id != 'null' && !empty($uson_id)){
            $where['uson_id'] = $uson_id;
        }
        $info = Db::name('u_user')
            ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
            ->join('up_school', 'school_id = uson_school', 'left')
            ->where($where)
            ->field('user_id, username, user_phone, user_username, school_name, user_time, user_status, 
            user_image,uson_username,uson_idcard,user_gender,uson_year,uson_grade')
            ->find();
        $money = Db::table('up_self_order')
            ->where('user_id',$user_id)
            ->where('is_pay',1)
            ->sum('total_price');
        $countorder = Db::table('up_self_order')
            ->where('user_id',$user_id)
            ->where('is_pay',1)
            ->count();
        $this->assign('info', $info);
        $this->assign('money', $money);
        $this->assign('countorder', $countorder);
        return $this->fetch('member/memberdetail');
    }
    /**
     * 编辑
     * @return mixed|\think\response\Json
     */
    public function memberedit(){
        $user_id = input('user_id');
        $uson_id = trim(input('uson_id'),' ');
        $where = [
            'user_id' => $user_id
        ];
        $disp = 1;
        if($uson_id != 'null' && !empty($uson_id)){
            $where['uson_id'] = $uson_id;
            $disp = 2;
        }
        if(Request::instance()->isPost()){
            $user_image = input('user_image');
            $user_username = input('user_username');
            $user_phone = input('user_phone');
            if(!preg_match("/^1[123456789]\d{9}$/", $user_phone)){
                return json(['code' => 100, 'msg' => '请输入正确的手机号']);
            }
            $update = [
                'user_image' => $user_image,
                'user_username' => $user_username,
                'user_phone' => $user_phone,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
            $data = Db::name('u_user')
                ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
                ->where($where)
                ->find();
            Db::startTrans();
            try{
                if($disp == 2){
                    $uson_username = input('uson_username');
                    $uson_idcard = input('uson_idcard');
                    $uson_year = input('uson_year');
                    $uson_class = input('uson_class');
                    $p_piano = input('p_piano');
                    $p_student = input('p_student');
                    if((int)$uson_year < 2014){
                        return json(['code' => 100, 'msg' => '只能输入大于2014且为数字类型的入学年份']);
                    }
                    $gname = Db::table('up_school_grade')->where('grade_id',$p_student)->value('grade_name');
                    $update2 = [];
                    $update2['uson_username'] = $uson_username;
                    $update2['uson_idcard'] = $uson_idcard;
                    $update2['uson_year'] = $uson_year;
                    $update2['uson_class'] = $uson_class;
                    $update2['uson_school'] = $p_piano;
                    $update2['uson_grade_id'] = $p_student;
                    $update2['uson_grade'] = $gname;
                    $update2['uson_update_time'] = date('Y-m-d H:i:s');
                    if($uson_idcard == ''){
                        $update['user_son_id'] = 0;
                    }else{
                        if($data['uson_idcard'] != $uson_idcard){
                            $have2 = Db::name('u_user_son')
                                ->where('uson_idcard',$uson_idcard)
                                ->find();
                            if($have2){
                                return json(['code' => 100, 'msg' => '已经有此身份证号了']);
                            }
                            //
                            if($uson_idcard != 'S407129A') {
                                $isrr = $this->is_idcard( $uson_idcard );
                                if($isrr == false){
                                    return json(['code' => 100, 'msg' => '请输入正确的身份证号']);
                                }
                                $age = date('Y') - substr($uson_idcard, 6, 4) - (date('md') >= substr($uson_idcard, 10, 4) ? 0 : 1);
                                if ($age < 5 || $age > 20) {
                                    return json_encode(['status' => 1, 'msg' => '年龄太大，请核实学生身份证号']);
                                }
                                $sexint = (int)substr($uson_idcard, 16, 1);
                                $sexint = $sexint % 2 === 0 ? '2' : '1';
                                $update2['user_gender'] = $sexint;
                            }
                        }
                    }
                    Db::name('u_user_son')
                        ->where('uson_id',$uson_id)
                        ->update($update2);
                }
                if($data['user_phone'] != $user_phone){
                    $have1 = Db::name('u_user')
                        ->where('user_phone',$user_phone)
                        ->find();
                    if($have1){
                        return json(['code' => 100, 'msg' => '已经有此手机号了']);
                    }
                }
                Db::name('u_user')
                    ->where('user_id',$user_id)
                    ->update($update);
                Db::commit();
                return json(['code' => 200, 'msg' => '编辑成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $info = Db::name('u_user')
            ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
            ->join('up_school', 'school_id = uson_school', 'left')
            ->where($where)
            ->find();
        $schools = [];
        $grades = [];
        if($disp == 2){
            $schools = Db::table('up_school')
                ->field('school_id,school_name')
                ->select();
            $scherp = Db::table('up_school')->where('school_id',$info['uson_school'])->value('school_erp');
            $grades = Db::table('up_school_grade')
                ->where('grade_school_erp',$scherp)
                ->order('grade_level asc')
                ->field('grade_id,grade_name')
                ->select();
        }

        $this->assign([
            'info' => $info,
            'user_id' => $user_id,
            'uson_id' => $uson_id,
            'disp' => $disp,
            'schools' => $schools,
            'grades' => $grades,
        ]);
        return $this->fetch('member/edit');
    }
    public function is_idcard( $id )
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
        else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return FALSE;
            }
            else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ( $i = 0; $i < 17; $i++ )
                {
                    $b = (int) $id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id,17, 1))
                {
                    return FALSE;
                }
                else
                {
                    return TRUE;
                }
            }
        }

    }
    /**
     * 根据学校获取对应的年级
     * @return mixed
     */
    public function getGradeBySchool(){
        if(Request::instance()->isPost()){
            $scherp = Db::table('up_school')->where('school_id',$_POST['pid'])->value('school_erp');
            $grades = Db::table('up_school_grade')
                ->where('grade_school_erp',$scherp)
                ->order('grade_level asc')
                ->field('grade_id id,grade_name name')
                ->select();
            return json(['code' => 200, 'msg' => $grades]);
        }
    }
	public function excelOut()
    {
        set_time_limit(0);//防止超时
        // ini_set("memory_limit", "256M");//防止内存溢出
        $where['user_status'] = ['neq', 3];
            $where['uson_status'] = ['neq', 3];
            $keyword = input('keyword');
            $start = input('start');
            $end = input('end');
            $user_school = input('user_school');
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|uson_username|uson_idcard'] = ['like', '%' . $keyword . '%'];
            }
            
            if(isset($start) && $start != "" && isset($end) && $end == "")
            {
                $where['uson_year'] = ['>=',$start];
            }
            if(isset($end) && $end != "" && isset($start) && $start == "")
            {
                $where['uson_year'] = ['<=',$end];
            }
            if(isset($start) && $start != "" && isset($end) && $end != "")
            {
                $where['uson_year'] = ['between',[$start,$end]];
            }
            
            if(isset($user_school) && $user_school != "")
            {
                $where['uson_school'] = $user_school;
            }
        $field = ['uson_username','user_gender','school_name','uson_year', 'uson_grade',
            'uson_height','uson_weight','uson_parent_phone','user_time'
        ];
//        $data = Db::name('u_user')
//                ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
//                ->join('up_school', 'school_id = uson_school', 'left')
//                ->where($where)
//                ->field($field)
//                ->select();
        $data = Db::name('u_user')
                ->join('up_u_user_son', 'user_id = uson_user_id', 'left')
                ->join('up_school', 'school_id = uson_school', 'left')
                ->where($where)
                ->field($field)
                ->count();
        if($data){
            $cellname = [
                '姓名','性别', '学校名字', '入学年份', '年级',
                '身高', '体重', '父母电话', '注册时间'

            ];
            $status = ['user_gender'];
            $values = [
                'user_gender' => [1 => '男',2 => '女']
            ];
            $res = exportExcelMember('userinfo',time(),$cellname,$data,$status,$values,2,ceil($data/10000),$where,$field);
//            $res = exportExcel('userDatas',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}